package algorithms;

import java.io.IOException;

import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.Reducer.Context;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;

public class PageRankFormatter extends Configured implements Tool {
	private static final Logger LOG = Logger.getLogger(PageRankFormatter.class);
	
	/**
	 * Convert edgelist into a format suitable for page rank.
	 */
	public static class Map extends Mapper<LongWritable, Text, Text, Text> {

		public void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
				
			String nodes[] = value.toString().trim().split("\t");
			
			context.write(new Text(nodes[0]), new Text(nodes[1]));
			context.write(new Text(nodes[1]), new Text(nodes[0]));
		}
	}
	
	/**
	 * Output:  index.html      <pagerank>      a.html  b.html  c.html  ...
	 */
	public static class Reduce extends Reducer<Text, Text, Text, Text>   {
		
		public void reduce(Text key, Iterable<Text> values, Context context)
				throws IOException, InterruptedException {
			
			String node = key.toString();
			String neighbors = "1.0\t";
			for (Text value : values) {
				neighbors += value.toString() + "\t";
			}
			neighbors = neighbors.trim();
	
			context.write(key, new Text(neighbors));
		}
	}

	@Override
	public int run(String[] args) throws Exception {

		String inputPath = args[0];
		String outputPath = args[1] + "/output-0";// + "_tmp";
		int n = Integer.parseInt(args[2]);

		LOG.info("Tool name: PageRankFormatter");
		LOG.info(" - inputDir: " + inputPath);
		LOG.info(" - outputDir: " + outputPath);
		LOG.info(" - src: " + n);

		Job job = new Job(getConf(), "PageRankFormatter");
		job.setJarByClass(PageRankFormatter.class);

		job.setNumReduceTasks(n);

		job.getConfiguration().setInt("src", n);

		FileInputFormat.addInputPath(job, new Path(inputPath));
		FileOutputFormat.setOutputPath(job, new Path(outputPath));

		job.setInputFormatClass(TextInputFormat.class);
		job.setOutputFormatClass(TextOutputFormat.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);
		
		/*
		job.setMapOutputKeyClass(TextInputFormat.class);
		job.setMapOutputValueClass(TextInputFormat.class);
		job.setOutputKeyClass(TextInputFormat.class);
		job.setOutputValueClass(TextInputFormat.class);*/

		job.setMapperClass(PageRankFormatter.Map.class);
		job.setReducerClass(PageRankFormatter.Reduce.class);
		
		// Delete the output directory if it exists already.
		FileSystem.get(job.getConfiguration()).delete(new Path(outputPath),
				true);
		
		boolean result = job.waitForCompletion(true);

		return result ? 0 : 1;
	}

	public static void main(String[] args) throws Exception {
		int res = ToolRunner.run(new PageRankFormatter(), args);
		System.exit(res);
	}
}
